package myservice.android.activities;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ReportsMonthActivity extends Activity {
	
	private Button sendSmsButton;
	private LinearLayout creditTimeSection;
	private TextView bookCount, brochureCount, ministryTime, creditTime, magazineCount, returnCallCount, bibleStudyCount;
	private Button previousMonthButton, nextMonthButton;	
	private TextView currentMonthText;	
	
	private String ministryTimeNoSpareMinutes;
	
	private int selectedMonth, selectedYear;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);                
        setContentView(R.layout.reports_month);           
        
    	Bundle extras = getIntent().getExtras();
    	if (extras != null) {
    		selectedMonth = extras.getInt("month");
    		selectedYear = extras.getInt("year");
    	}         
    	
    	sendSmsButton = (Button) findViewById(R.id.sendSmsButton);
    	creditTimeSection = (LinearLayout) findViewById(R.id.creditTimeSection);
    	bookCount = (TextView) findViewById(R.id.bookCount);    	
    	brochureCount = (TextView) findViewById(R.id.brochureCount);    	
    	ministryTime = (TextView) findViewById(R.id.fieldMinistryTime);    	
    	creditTime = (TextView) findViewById(R.id.creditTime);    	
    	magazineCount = (TextView) findViewById(R.id.magazineCount);    	
    	returnCallCount = (TextView) findViewById(R.id.returnCallCount);    	
    	bibleStudyCount = (TextView) findViewById(R.id.bibleStudyCount);    	
    	currentMonthText = (TextView) findViewById(R.id.selectedMonth);  
        previousMonthButton = (Button) findViewById(R.id.previousButton);
        nextMonthButton = (Button) findViewById(R.id.nextButton);    	
    	
		previousMonthButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				switchMonth(-1);				
			}			
		});
		
		nextMonthButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				switchMonth(1);				
			}			
		});	   
		
		// Check if telephony is available; hide the button if not
		PackageManager pm = this.getPackageManager();
		if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY))
			sendSmsButton.setVisibility(View.GONE);
		else		
			sendSmsButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					try {
						Intent smsIntent = new Intent( Intent.ACTION_VIEW);
						
						//Construct the sms message from the template
						String message = new String(Global.smsTemplate);
						message=message.replace("$1", Global.monthNames[selectedMonth]);					
						message=message.replace("$2", bookCount.getText());
						message=message.replace("$3", brochureCount.getText());
						message=message.replace("$4", ministryTimeNoSpareMinutes);
						message=message.replace("$5", magazineCount.getText());
						message=message.replace("$6", returnCallCount.getText());
						message=message.replace("$7", bibleStudyCount.getText());
						message=message.replace("$8", creditTime.getText());
						
						smsIntent.putExtra("sms_body", message);
						smsIntent.setType("vnd.android-dir/mms-sms");
						startActivity(smsIntent);
					} catch (Exception e) {
						Global.displayToast(ReportsMonthActivity.this, Global.res.getString(R.string.message_sms_failed));
					}
				}			
			});	  		

	}
    
    @Override
    public void onResume() {
    	super.onResume();
    	updateUi();
    }
    
    private void updateUi() {
    	
		currentMonthText.setText(Global.monthNames[selectedMonth]+" "+selectedYear);
		
		// count spare minutes from previous months
		Cursor cursor = Database.select("SELECT SUM(minutes) AS m FROM ministry WHERE year<"+selectedYear+" OR (year="+selectedYear+" AND month<"+selectedMonth+")");
		cursor.moveToNext();
		int spareMinutes = cursor.getInt(cursor.getColumnIndex("m")) % 60;
		cursor.close();
		
		cursor = Database.select("SELECT SUM(hours) AS h, SUM(minutes) AS m, SUM(chours) AS ch, SUM(cminutes) AS cm, SUM(magazines) AS mag, SUM(brochures) AS br, SUM(books) AS bk, "+
		                                "SUM(returncalls) AS rc FROM ministry WHERE month="+selectedMonth+" AND year="+selectedYear);
		cursor.moveToNext();	
		
		bookCount.setText(""+cursor.getInt(cursor.getColumnIndex("bk")));
		brochureCount.setText(""+cursor.getInt(cursor.getColumnIndex("br")));
		returnCallCount.setText(""+cursor.getInt(cursor.getColumnIndex("rc")));
		magazineCount.setText(""+cursor.getInt(cursor.getColumnIndex("mag")));			
		
		// calculate ministry time (spare minutes are transferred to the next months)
		int ministryMinutes = cursor.getInt(cursor.getColumnIndex("h"))*60 + cursor.getInt(cursor.getColumnIndex("m")) + spareMinutes;
		int spareMinutesCount = ministryMinutes % 60;
		String spareMinutesText = "";
		if (spareMinutesCount != 0)
			spareMinutesText=getString(R.string.label_monthly_spare_minutes,spareMinutesCount);
		ministryTime.setText(ministryMinutes/60+" "+Global.res.getString(R.string.label_hour_short)+" "+spareMinutesText);
		ministryTimeNoSpareMinutes=ministryMinutes/60+" "+Global.res.getString(R.string.label_hour_short); // for sms
		
		// calculate credit time (spare minutes are not transferred)
		int creditMinutes = cursor.getInt(cursor.getColumnIndex("ch"))*60 + cursor.getInt(cursor.getColumnIndex("cm"));
		if (creditMinutes==0 && Global.trackCreditTime==false)
			creditTimeSection.setVisibility(View.GONE);
		else {
			creditTimeSection.setVisibility(View.VISIBLE);
			creditTime.setText(creditMinutes/60+" "+Global.res.getString(R.string.label_hour_short)+" "+creditMinutes % 60+" "+Global.res.getString(R.string.label_minute_short));
		}
		
		cursor.close();
		
		// calculate individual Bible students (status=Bible student, and at least one call marked as Bible study was conducted in that month)
		cursor = Database.select("SELECT DISTINCT name FROM persons JOIN calls ON persons.personid=calls.personid WHERE status=3 AND persons.timestamp<>"+Global.TIMESTAMP_DELETED+
				                 " AND biblestudy=1 AND month="+selectedMonth+" AND year="+selectedYear);
		bibleStudyCount.setText(""+cursor.getCount());
		cursor.close();
    	
    }
    
	private void switchMonth(int direction) {
		selectedMonth=selectedMonth+direction;
		
		if (selectedMonth<0) {
			selectedMonth=11;
			selectedYear--;
		}
		
		if (selectedMonth>11) {
			selectedMonth=0; selectedYear++;
		}
		
		updateUi();
		
	}    

}